//
//  ViewController.swift
//  6.4.Displaying a Refresh Control for Table Views
//
//  Created by joker on 15/8/8.
//  Copyright (c) 2015年 joker. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UITableViewDataSource {

    var tableView: UITableView?
    
    var allItems = [NSDate]()
    
    var refreshControl: UIRefreshControl?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        allItems.append(NSDate())
        
        tableView = UITableView(frame: view.bounds, style: .Plain)
        
        if let theTableView = tableView {
            theTableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "identifier")
            theTableView.dataSource = self
            theTableView.autoresizingMask = .FlexibleWidth | .FlexibleHeight
            
            refreshControl = UIRefreshControl()
            
            refreshControl?.addTarget(self, action: "handleRefresh:", forControlEvents: .ValueChanged)
            
            theTableView.addSubview(refreshControl!)
            
            view.addSubview(theTableView)
        }
    }
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1;
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return allItems.count;
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("identifier", forIndexPath: indexPath) as! UITableViewCell
        cell.textLabel?.text = allItems[indexPath.row].description
        return cell
    }
    
    func handleRefresh(paramSender: AnyObject){
        let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_MSEC))
        
        dispatch_after(popTime, dispatch_get_main_queue(), {
        
            self.allItems.append(NSDate() )
            self.refreshControl?.endRefreshing()
            let indexPathOfNewRow = NSIndexPath(forRow: self.allItems.count - 1, inSection: 0)
            
            self.tableView!.insertRowsAtIndexPaths([indexPathOfNewRow], withRowAnimation: .Automatic)
        })
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

